import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.security.*;
public class Skey_kb{//shengchenmiyao
    public void createKey() throws Exception{
        KeyGenerator kg=KeyGenerator.getInstance("DESede");
        kg.init(168);
        SecretKey k=kg.generateKey( );
        FileOutputStream  f=new FileOutputStream("key1.dat");
        ObjectOutputStream b=new  ObjectOutputStream(f);
        b.writeObject(k);
    }
    public void getByteKey() throws Exception{

        FileInputStream f=new FileInputStream("key1.dat");
        ObjectInputStream b=new ObjectInputStream(f);
        Key k=(Key)b.readObject( );
        byte[ ] kb=k.getEncoded( );
        FileOutputStream  f2=new FileOutputStream("keykb1.dat");
        f2.write(kb);
        // 打印密钥编码中的内容
        for(int i=0;i<kb.length;i++){
            System.out.print(kb[i]+",");
        }

    }
    public String enc(String m) throws Exception{
        String s=m;

        FileInputStream f=new FileInputStream("key1.dat");
        ObjectInputStream b=new ObjectInputStream(f);
        Key k=(Key)b.readObject( );
        Cipher cp=Cipher.getInstance("DESede");
        cp.init(Cipher.ENCRYPT_MODE, k);
        byte ptext[]=s.getBytes("UTF8");
        for(int i=0;i<ptext.length;i++){
            System.out.print(ptext[i]+",");
        }
        System.out.println("");
        byte ctext[]=cp.doFinal(ptext);
        String out=ByteToHex.parseByte2HexStr(ctext);

        for(int i=0;i<ctext.length;i++){
            System.out.print(ctext[i] +",");
        }
        System.out.println();
        return out;
       /* FileOutputStream f2=new FileOutputStream("SEnc.dat");
        f2.write(ctext);*/
    }
    public String dec(String c) throws Exception{
        // 获取密文
       /* FileInputStream f=new FileInputStream("SEnc.dat");*/
       /* int num=f.available();*/


       /* byte[ ] ctext=new byte[num];*/

        byte[ ] ctext=HexToByte.parseHexStr2Byte(c);
        /*f.read(ctext);*/
        // 获取密钥
        FileInputStream  f2=new FileInputStream("keykb1.dat");
        int num2=f2.available();
        byte[ ] keykb=new byte[num2];
        f2.read(keykb);
        SecretKeySpec k=new  SecretKeySpec(keykb,"DESede");
        // 解密
        Cipher cp=Cipher.getInstance("DESede");
        cp.init(Cipher.DECRYPT_MODE, k);
        byte []ptext=cp.doFinal(ctext);
        // 显示明文
        String p=new String(ptext,"UTF8");
        System.out.println(p);
        return p;
    }
}